package com.captjack.wechat.admin.controller;

import com.captjack.wechat.admin.entity.User;
import com.captjack.wechat.admin.repository.SysDictRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.UUID;

/**
 * @author Capt Jack
 * @date 2018/5/22
 */
@RestController
@RequestMapping(value = "/hello")
public class HelloController {

    private final RedisTemplate redisTemplate;

    private final SysDictRepository sysDictRepository;

    @GetMapping(value = "/hello")
    public String hello(@Valid User user, BindingResult bindingResult, HttpServletRequest request) {
        System.out.println(request.getSession().getAttribute("session").toString());
        if (bindingResult.hasErrors()) {
            return bindingResult.getFieldErrors().get(0).getDefaultMessage();
        }
        return (String) redisTemplate.opsForValue().get("sptd-tkt-14200000576");
    }

    @GetMapping(value = "/hello1")
    public Object hello1(@RequestParam int pageNo, @RequestParam int pageSize, HttpServletRequest request) {
        pageNo = pageNo <= 0 ? 0 : pageNo - 1;
        pageSize = pageSize < 0 ? 5 : pageSize;
        request.getSession().setAttribute("session", UUID.randomUUID().toString());
        return sysDictRepository.findAll(PageRequest.of(pageNo, pageSize));
    }

    @Autowired
    public HelloController(RedisTemplate redisTemplate, SysDictRepository sysDictRepository) {
        this.redisTemplate = redisTemplate;
        this.sysDictRepository = sysDictRepository;
    }

}
